import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
const apiLogin = uniCloud.importObject('qc-login', { customUI: true });
/**
 * @description  忘记密码逻辑封装（通过手机号重置密码）
 * @param rules 表单校验规则
 * */
export const useResetPwd = (formRefs, captchaRef, rules) => {
	const state = reactive({
		formData: {
			mobile: '', //手机号
			code: '', //验证码	
			password: "", //密码
			password2: '', //对比密码
			captcha: '', //图形验证码
		},
		formItem: {
			loading: false, //防抖状态
			needCaptcha: false, //显示隐藏验证码状态
		},
		// 校验规则
		rules,
		// 图片验证url
		url: '',
		pictureVerify: ['../../../static/login/0.jpg', '../../../static/login/1.jpg', '../../../static/login/2.jpg', '../../../static/login/3.jpg']
	})
	onLoad((e) => {
		function generateRandomInteger(min, max) {
			return Math.floor(Math.random() * (max - min + 1)) + min;
		}
		state.url = state.pictureVerify[generateRandomInteger(0, 4)]
	})
	// 兼容H5
	onShow(() => {
		// #ifdef H5
		document.onkeydown = event => {
			var e = event || window.event;
			if (e && e.keyCode == 13) { //回车键的键值为13
				submit()
			}
		};
		// #endif
	})
	onReady(() => {
		// 兼容小程序的校验 (uview中使用)
		if (formRefs.value.setRules) formRefs.value.setRules(state.rules)
	});


	// 卸载键盘事件
	onUnload(() => {
		// #ifdef H5
		document.onkeydown = false
		// #endif
	});


	/***
	 * @description: 点击获取短信验证码
	 * @param {*}
	 * @return {*}
	 * @author: white_queen
	 */
	const toSmsPage = async () => {
		try {
			const isPhone = computed(() => /^1\d{10}$/.test(state.formData.mobile))
			if (!isPhone.value) {
				return uni.showToast({
					title: "手机号码格式不正确",
					icon: 'none',
					duration: 3000
				});
			}
			// 发送短信
			return await apiLogin.sendSmsCode({ mobile: state.formData.mobile, scene: "reset-pwd-by-sms" })
		} catch (e) {
			console.log(e.message);
		}
	}




	/**
	 * @description: 忘记密码
	 * @param {*} formRef 表单实例
	 * @param {*} captchaRef 验证码实例
	 */
	const submit = async () => {
		formRefs.value.validator(state.formData, rules).then(async res => {
			// 如果没有输入验证码并且显示的有验证码输入提示 就提示输入验证码
			if (state.formData.captcha.length != 4 && state.formItem.needCaptcha) {
				// 让验证码输入框获取焦点
				captchaRef.value.focusCaptchaInput = true
				return uni.showToast({
					title: '请输入验证码',
					icon: 'none',
					duration: 3000
				});
			}
			if (!res.isPassed) return
			try {
				const res = await uniIdCo.resetPwdBySms({
					mobile: state.formData.mobile,
					code: state.formData.code,
					password: state.formData.password2,
					captcha: state.formData.captcha
				})
				if (res.errCode == 0) {
					uni.fui.toast('重置成功')
					toLoing()
				}
			} catch (e) {
				// 如果输入密码输入错误多次 就提示图形验证码
				if (e.errCode == 'uni-id-captcha-required') {
					state.formItem.needCaptcha = true
				} else if (state.formItem.needCaptcha) {
					//登录失败，自动重新获取验证码
					captchaRef.value.getImageCaptcha()
				}
				uni.fui.toast(e.errMsg)
			}

		})
	}

	// 去登录
	const toLoing = () => {
		uni.navigateBack()
	}

	return {
		...toRefs(state),
		submit,
		toSmsPage,
		toLoing
	};
};